package org.fhm.zdte.common.constant.protocol;


import org.fhm.zdte.common.exception.ProtocolException;

import java.util.Arrays;
import java.util.Objects;

/**
 * The type of Data-Package.
 *
 * @author 谭波
 * @since 2023/10/31
 */
public enum PacketType {

    ONLINE((byte) 0b00000001, "ONLINE"),
    ONLINE_CHECK((byte) 0b00000010, "ONLINE_CHECK"),
    CONNECT((byte) 0b00000011, "CONNECT"),
    HEARTBEAT((byte) 0b0000100, "HEARTBEAT"),
    REQUEST((byte) 0b0000101, "REQUEST");

    private final Byte valueBit;

    private final String name;

    PacketType(Byte valueBit, String name) {
        this.valueBit = valueBit;
        this.name = name;
    }

    public static Boolean isPacketType(PacketType type) {
        if (Objects.isNull(type)) {
            throw new ProtocolException("the Byte of packet type error");
        }
        return Arrays.asList(
                PacketType.values()
        ).contains(type);
    }

    public static PacketType getPacketType(Byte valueBit) {
        if (Objects.isNull(valueBit))
            throw new ProtocolException("the Byte of packet type error");
        for (PacketType packetType : PacketType.values()) {
            if (packetType.valueBit.equals(valueBit))
                return packetType;
        }
        throw new ProtocolException("there is no matching packet type for Byte");
    }

    public static String getPacketNameBy(PacketType type) {
        if (Objects.isNull(type)) {
            throw new ProtocolException("the Byte of packet type error");
        }
        for (PacketType p : PacketType.values()) {
            if (p.equals(type)) {
                return p.name;
            }
        }
        throw new ProtocolException("there is no matching packet type for Byte");
    }

    public Byte getValueBit() {
        return valueBit;
    }


    public String getName() {
        return name;
    }
}
